//
//  BFNewsController.m
//  beifang
//
//  Created by Apple on 17/4/12.
//  Copyright © 2017年 郭凯. All rights reserved.
//

#import "BFNewsController.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>
#import <AddressBook/AddressBook.h>
#import <APContact.h>
#import "BFMapViewController.h"
#import "BDMapController.h"
#import "BFCaptureController.h"
@interface BFNewsController ()<CNContactPickerDelegate>

@end

@implementation BFNewsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blueColor];
    self.title = @"最新资讯";
}
- (void)requestAuthorizationAddressBook {
    // 判断是否授权
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus == kABAuthorizationStatusNotDetermined) {
        // 请求授权
        ABAddressBookRef addressBookRef = ABAddressBookCreate();
        ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
            if (granted) { // 授权成功
                
            } else {  // 授权失败
                NSLog(@"授权失败！");
            }
        });
    }
}
    
- (IBAction)contact:(id)sender {
//    CNContactPickerViewController *picker = [[CNContactPickerViewController alloc]init];
//    picker.delegate = self;
//    [self presentViewController:picker animated:YES completion:nil];
    // 1. 判读授权
//    [self getAddressBookByKuangjia];
    [self getContacts];
}



-(void)getContacts{
    //判断授权状态
    if ([CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts] == CNAuthorizationStatusNotDetermined) {
        
        CNContactStore *store = [[CNContactStore alloc] init];
        [store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"授权成功");
                // 2. 获取联系人仓库
                CNContactStore * store = [[CNContactStore alloc] init];
                
                // 3. 创建联系人信息的请求对象
                NSArray * keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
                
                // 4. 根据请求Key, 创建请求对象
                CNContactFetchRequest * request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
                
                // 5. 发送请求
                [store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
                    
                    // 6.1 获取姓名
                    NSString * givenName = contact.givenName;
                    NSString * familyName = contact.familyName;
                    NSLog(@"%@--%@", givenName, familyName);
                    
                    // 6.2 获取电话
                    NSArray * phoneArray = contact.phoneNumbers;
                    for (CNLabeledValue * labelValue in phoneArray) {
                        
                        CNPhoneNumber * number = labelValue.value;
                        NSLog(@"%@--%@", number.stringValue, labelValue.label);
                    }
                }];
            } else {
                NSLog(@"授权失败");
            }
        }];
    }
}

-(void)getAddressBookByKuangjia{

    APAddressBook *addressBook = [[APAddressBook alloc] init];
    [addressBook loadContacts:^(NSArray <APContact *> *contacts, NSError *error)
    {
        // hide activity
        if (error)
        {
        }
        else
        {
            for (APContact *contact in contacts) {
                
                for (APPhone *phone in contact.phones) {
                    NSLog(@"%@",phone.number);
                }
            }
        }
    }];

}
-(void)getABAddressBook{
    [self requestAuthorizationAddressBook];
    ABAuthorizationStatus authorizationStatus = ABAddressBookGetAuthorizationStatus();
    if (authorizationStatus != kABAuthorizationStatusAuthorized) {
        NSLog(@"没有授权");
        return;
    }
    
    // 2. 获取所有联系人
    ABAddressBookRef addressBookRef = ABAddressBookCreate();
    CFArrayRef arrayRef = ABAddressBookCopyArrayOfAllPeople(addressBookRef);
    long count = CFArrayGetCount(arrayRef);
    for (int i = 0; i < count; i++) {
        //获取联系人对象的引用
        ABRecordRef people = CFArrayGetValueAtIndex(arrayRef, i);
        
        //获取当前联系人名字
        NSString *firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        
        //获取当前联系人姓氏
        NSString *lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
        NSLog(@"--------------------------------------------------");
        NSLog(@"firstName=%@, lastName=%@", firstName, lastName);
        
        //获取当前联系人的电话 数组
        NSMutableArray *phoneArray = [[NSMutableArray alloc]init];
        ABMultiValueRef phones = ABRecordCopyValue(people, kABPersonPhoneProperty);
        for (NSInteger j=0; j<ABMultiValueGetCount(phones); j++) {
            NSString *phone = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j));
            NSLog(@"phone=%@", phone);
            [phoneArray addObject:phone];
        }
        
        //获取当前联系人的邮箱 注意是数组
        NSMutableArray *emailArray = [[NSMutableArray alloc]init];
        ABMultiValueRef emails= ABRecordCopyValue(people, kABPersonEmailProperty);
        for (NSInteger j=0; j<ABMultiValueGetCount(emails); j++) {
            NSString *email = (__bridge NSString *)(ABMultiValueCopyValueAtIndex(emails, j));
            NSLog(@"email=%@", email);
            [emailArray addObject:email];
        }
//        //获取当前联系人中间名
//        NSString *middleName=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNameProperty));
//        //获取当前联系人的名字前缀
//        NSString *prefix=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonPrefixProperty));
//        
//        //获取当前联系人的名字后缀
//        NSString *suffix=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonSuffixProperty));
//        
//        //获取当前联系人的昵称
//        NSString *nickName=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonNicknameProperty));
//        
//        //获取当前联系人的名字拼音
//        NSString *firstNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonFirstNamePhoneticProperty));
//        
//        //获取当前联系人的姓氏拼音
//        NSString *lastNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonLastNamePhoneticProperty));
//        
//        //获取当前联系人的中间名拼音
//        NSString *middleNamePhoneic=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonMiddleNamePhoneticProperty));
//        
//        //获取当前联系人的公司
//        NSString *organization=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonOrganizationProperty));
//        
//        //获取当前联系人的职位
//        NSString *job=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonJobTitleProperty));
//        
//        //获取当前联系人的部门
//        NSString *department=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonDepartmentProperty));
//        
//        //获取当前联系人的生日
//        NSString *birthday=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonBirthdayProperty));
//        
//        //获取当前联系人的备注
//        NSString *notes=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonNoteProperty));
//        
//        //获取创建当前联系人的时间 注意是NSDate
//        NSDate *creatTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonCreationDateProperty));
//        
//        //获取最近修改当前联系人的时间
//        NSDate *alterTime=(__bridge NSDate*)(ABRecordCopyValue(people, kABPersonModificationDateProperty));
//        
//        //获取地址
//        ABMultiValueRef address = ABRecordCopyValue(people, kABPersonAddressProperty);
//        for (int j=0; j<ABMultiValueGetCount(address); j++) {
//            //地址类型
//            NSString *type = (__bridge NSString *)(ABMultiValueCopyLabelAtIndex(address, j));
//            NSDictionary * tempDic = (__bridge NSDictionary *)(ABMultiValueCopyValueAtIndex(address, j));
//            //地址字符串，可以按需求格式化
//            NSString *adress = [NSString stringWithFormat:@"国家:%@\n省:%@\n市:%@\n街道:%@\n邮编:%@",[tempDic valueForKey:(NSString*)kABPersonAddressCountryKey],[tempDic valueForKey:(NSString*)kABPersonAddressStateKey],[tempDic valueForKey:(NSString*)kABPersonAddressCityKey],[tempDic valueForKey:(NSString*)kABPersonAddressStreetKey],[tempDic valueForKey:(NSString*)kABPersonAddressZIPKey]];
//        }
        
        //获取当前联系人头像图片
        NSData *userImage=(__bridge NSData*)(ABPersonCopyImageData(people));
        //获取当前联系人纪念日
        NSMutableArray *dateArr = [[NSMutableArray alloc]init];
        ABMultiValueRef dates= ABRecordCopyValue(people, kABPersonDateProperty);
        for (NSInteger j=0; j<ABMultiValueGetCount(dates); j++) {
            //获取纪念日日期
            NSDate *data =(__bridge NSDate*)(ABMultiValueCopyValueAtIndex(dates, j));
            //获取纪念日名称
            NSString *str =(__bridge NSString*)(ABMultiValueCopyLabelAtIndex(dates, j));
            NSDictionary *tempDic = [NSDictionary dictionaryWithObject:data forKey:str];
            [dateArr addObject:tempDic];
        }
    }

}
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact*> *)contacts{
    NSLog(@"%@",contacts);
    
    for (CNContact *contact in contacts) {
        for (CNLabeledValue *labeldValue in contact.phoneNumbers) {
            CNPhoneNumber *number = labeldValue.value;
            NSLog(@"电话号码=%@",number.stringValue);
        }
    }

}
- (IBAction)getMap:(id)sender {
    BFMapViewController *mapVc = [[BFMapViewController alloc]init];
    [self.navigationController pushViewController:mapVc animated:YES];
}


- (IBAction)baidu:(id)sender {
    BDMapController *bdVC =[[BDMapController alloc]init];
    [self.navigationController pushViewController:bdVC animated:YES];
}
- (IBAction)caiji:(id)sender {
    BFCaptureController *captureVC = [[BFCaptureController alloc]init];
    [self.navigationController pushViewController:captureVC  animated:YES];
}
@end
